<template>
  <div class="pd30 flex flexjcsb">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>角色管理</div>
        <!-- <el-button class="addBtn fw defaultbtn"  type="primary">添加</el-button> -->
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <!-- <div class="inputLable inputLable1 flex flexac">
            <el-input v-model="queryParam.companyId" class="input" placeholder="请输入地产品牌ID..." />
          </div> -->
          <div class="inputLable inputLable2 flex flexac">
            公司：
            <el-input v-model="companyName" readonly placeholder="请选择所属公司..." />
            <el-button type="warning" class="comp-select m-l-20 iconfont icon-xuanze" @click="handleSelect">选择公司</el-button>
            <!-- <el-input v-model="queryParam.roleName" class="input" placeholder="请输入角色名称..." /> -->
          </div>
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>
          <div class="m-r-25 flex">
            <el-button class="defaultbtn" type="primary" @click="handleAdd"><i class="el-icon-circle-plus-outline" />添加新角色</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-shezhi" />字段
              </el-button>
              <div class="selectUl" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">

                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-shezhi" />排序</el-button>
              <div class="selectUl" :class="seniorSet.sortable ? 'showSelectUl' : 'hideSelectUl'">

                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <!-- <el-button class="defaultbtn" @click="handleExportExcel" type="primary"><i class="iconfont icon-shezhi"></i>固定</el-button> -->
          </div>
        </div>

        <el-table
          id="dataList"
          ref="dataList"
          class="con-table"
          type="expand"
          :data="dataList"
          highlight-current-row
        >
          <!-- <el-table-column width="90" type="selection" label="全选" /> -->

          <template v-for="item in tablehead">
            <el-table-column v-if="item.isShow" :key="item.index" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
          </template>

          <el-table-column label="数据权限" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.dataScope === 1 ? '本人' : scope.row.dataScope === 2 ? '本机构' : '本机构及下级机构' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="是否管理员角色" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.isAdmin ? '是' : '否' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.roleStatus ? '启用' : '禁用' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" width="200">
            <template slot-scope="scope">
              <span>
                {{ `${scope.row.crtDate[0]} -
                ${scope.row.crtDate[1] < 10 ? '0' + scope.row.crtDate[1] : scope.row.crtDate[1]} -
                ${scope.row.crtDate[2] < 10 ? '0' + scope.row.crtDate[2] : scope.row.crtDate[2]} &nbsp;
                ${scope.row.crtDate[3] < 10 ? '0' + scope.row.crtDate[3] : scope.row.crtDate[3]} :
                ${scope.row.crtDate[4] < 10 ? '0' + scope.row.crtDate[4] : scope.row.crtDate[4]} :
                ${scope.row.crtDate[5] < 10 ? '0' + scope.row.crtDate[5] : scope.row.crtDate[5]}` }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="name" align="center" width="200" label="基本操作">
            <template slot-scope="scope">
              <el-button class="defaultbtn" type="primary" plain @click="handleEdit(scope.$index, scope.row)">
                <i class="el-icon-edit" />编辑</el-button>
              <el-popconfirm
                title="确定要删除角色吗？"
                @onConfirm="handleRoleConfirm(scope.$index, scope.row, dataList)"
                @onCancel="handlRoleCancel(scope.$index, scope.row)"
              >
                <el-button slot="reference" class="defaultbtn" type="danger" plain>
                  <i class="el-icon-delete" />删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="paginationWrap flex"
          :current-page="paging.currentPage"
          :page-sizes="paging.pageSizeArr"
          :page-size="paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <RoleEdit v-model="visible" class="authorityRole" :data="editRole" :is-edit="isEdit" @handleRefresh="onRoleAdd" @handleCloseDialog="handleCloseDialog" />
    <CoSelect v-model="coSelectVisible" @update="handleSelectUpdate" />
  </div>
</template>

<script>

import RoleEdit from './dialog/index'
import CoSelect from '@/components/coSelect/index'
// import { fetchRoleList, fetchRoleDelete, fetchRoleDetail } from '@/api/baseInfo/authority/role'
// import { fetchSystemCompanyId } from '@/api/baseInfo/authority/company'
import { showNotice, formatDateTime, transData } from '@/utils/toolclass'

export default {
  components: { RoleEdit, CoSelect },
  props: {},
  data() {
    return {
      paging: {
        currentPage: 1,
        pageSize: 10,
        pageSizeArr: [10, 15, 20, 35],
        total: 0
      },
      tablehead: [
        {
          index: 0,
          prop: 'roleName',
          label: '角色名称',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'orgName',
          label: '所属机构',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ],
      dataList: [],
      companyName: '',
      queryParam: {
        companyId: '',
        roleName: ''
      },
      value: '',
      company: [],
      options: [],
      visible: false,
      coSelectVisible: false,
      editRole: {},
      isEdit: false,
      refresh: false,
      seniorSet: {
        'field': false,
        'sortable': false
      }

    }
  },
  computed: {},
  watch: {},
  created() {
    // this.getSystemCompanyies()
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/authority/role/orgRole' }))
  },
  methods: {
    // getSystemCompanyies() {
    //   fetchCompanies().then(res => {
    //     this.options = res.data
    //     this.getRoleList(res.data[0].companyId)
    //   })
    // },
    // 查询所有公司弹窗
    handleSelect() {
      this.coSelectVisible = true
    },
    // 公司信息更新回调
    handleSelectUpdate(row) {
      this.queryParam.roleName = ''
      this.queryParam.companyId = row.companyId
      this.companyName = row.companyName
      this.getRoleList(this.queryParam.companyId, this.queryParam.roleName)
    },
    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['系统ID', '资源图标', '父资源', '资源ID', '资源名称', '资源顺序', '资源类型', '资源链接']
        const filterVal = ['sysId', 'iconUrl', 'parentId', 'resourceId', 'resourceName', 'resourceSort', 'resourceType', 'resourceUrl']
        const data = this.formatJson(filterVal, this.dataList)
        export_json_to_excel(tHeader, data, '系统平台权限资源表(' + formatDateTime().ymd) + ')'
      })
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh(res) {
      const data = this.options.filter(item => {
        if (item.companyName === this.companyName) {
          return item.companyId
        }
      })
      data.map(item => {
        this.queryParam = {
          companyId: parseInt(item.companyId),
          roleName: this.queryParam.roleName
        }
      })
      if (this.queryParam.companyId) {
        this.getRoleList(this.queryParam.companyId, this.queryParam.roleName)
        this.refresh = true
      } else {
        showNotice('error', '提示', '请选择公司!')
      }
    },
    onRoleAdd(res) {
      this.companyName = res.companyName
      this.queryParam.companyId = res.unitId
      this.getRoleList(res.unitId, '')
    },
    getRoleList(id, name) {
      fetchRoleList(id, name).then((res) => {
        if (res.code === '000000') {
          this.dataList = res.data
          this.paging = {
            currentPage: res.pager.pageIndex,
            pageSize: res.pager.pageSize,
            total: res.pager.totalSize
          }
        }
      })
    },
    handleRoleConfirm(index, row, rows) {
      if (row.unitId !== 1 && row.isAdmin === true) {
        showNotice('error', '提示', '管理员不能删除!')
      } else {
        fetchRoleDelete(row.id).then(res => {
          if (res.code === '000000') {
            showNotice('success', '提示', '删除成功!')
            rows.splice(index, 1)
          }
        })
      }
    },
    handlRoleCancel(index, row) {
      // console.log(index, row)
    },
    // getCompanyId(id) {
    //   fetchSystemCompanyId(id).then(res => {
    //     this.company = res.data
    //     return this.company
    //   })
    // },
    handleEdit(index, row) {
      this.visible = true
      this.isEdit = true
      fetchRoleDetail(row.id).then(res => {
        const role = res.data.role
        role.sysIdList.forEach(val => {
          this.info = res.data.systems.filter(item => {
            if (item.sysId === val) {
              this.checkSysiId = item.sysName
              return item
            }
          })
        })
        this.editRole = {
          id: role.id,
          unitId: role.unitId,
          orgId: role.orgId,
          sysIdList: this.info,
          orgName: role.orgName,
          roleName: role.roleName,
          isAdmin: role.isAdmin,
          dataScope: role.dataScope === 1 ? '本人' : role.dataScope === 2 ? '本机构' : '本机构及其下级机构',
          resourcesList: res.data.resourcesList,
          roleStatus: role.roleStatus ? '启用' : '禁用',
          crtDate: formatDateTime(role.crtDate).ymdhm,
          companyName: role.companyName,
          setTre: res.data.resourcesList,
          companyId: parseInt(this.queryParam.companyId),
          checkSysiId: this.checkSysiId,
          systems: res.data.systems
        }
      })
      // const item = this.options.filter(item => {
      //   if (parseInt(item.companyId) === row.unitId) {
      //     return item
      //   }
      // })

      // item.map(item => {
      //   this.params = {
      //     companyName: item.companyName,
      //     companyId: item.companyId
      //   }
      //   return this.params
      // })
      // const crtDate = `${row.crtDate[0]}${row.crtDate[1]}${row.crtDate[2]}${row.crtDate[3]}${row.crtDate[4]}${row.crtDate[5]}`

      // this.getCompanyId(parseInt(this.params.companyId))
    },
    handleAdd() {
      this.visible = true
      this.isEdit = false
      this.editRole = {
        crtDate: [],
        dataScope: '本人',
        id: 0,
        isAdmin: '',
        isTop: '',
        lstEdtDate: '',
        orgId: '',
        orgName: '',
        resourcesList: [],
        roleName: '',
        roleStatus: '',
        sysIdList: [],
        unitId: '',
        companyName: ''
      }
    },
    handleCloseDialog() {
      this.visible = !this.visible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/public.scss';
.errorImg {
  display: inline-block;
  width: 60px;
  height: 60px;
}
.menuLeft {
  margin-right: 20px;
  .panelWrap {
    height: 100%;
  }
}
.menuCon {
  width: 80%;
}

.show-btns {
  opacity: 1;
}

/* common end */

.comp-tree {
  width: 100%;
  max-width: 700px;
  max-height: 80vh;
  padding: 10px;
  overflow: auto;
  // 顶部按钮
  .comp-tr-top {
    width: 100px;
    margin-bottom: 2em;
  }
  // 自定义节点
  .comp-tr-node {
    // label
    .comp-tr-node--name {
      display: inline-block;
      line-height: 40px;
      min-height: 40px;
      // 新增
      &.is-new {
        // font-weight: bold;
      }
    }
    // button
    .comp-tr-node--btns {
      margin-left: 10px;
      opacity: 0;
      transition: opacity 0.1s;
      .el-button {
        transform: scale(0.8); // 缩小按钮
        & + .el-button {
          margin-left: -1px;
        }
      }
    }
  }
  // 高亮显示按钮
  .is-current {
    & > .el-tree-node__content {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
  // 悬浮显示按钮
  .el-tree-node__content {
    &:hover {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
}

.deleteBtn {
  margin-left: 5px !important;
}
.operationBtn {
  .defaultbtn {
    margin-left: 5px;
  }
}
</style>
